package com.windmill.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TextUtils {
    /**
	 * @param filePath
	 * @return
	 */
	public static String readText(String filePath){
		StringBuffer text = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new FileReader(filePath));
			String line = null;
			while((line=br.readLine())!=null){
				text.append(line);
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return text.toString();
	}
	/**
	 * @param filePath
	 * @return
	 */
	public static List<String> readLine(String filePath){
		List<String> listStr = new ArrayList<String>();
		if(new File(filePath).exists()){
			try {
				BufferedReader br = new BufferedReader(new FileReader(filePath));
				String line = null;
				while((line=br.readLine())!=null){
					listStr.add(line);
				}
				br.close();
			} catch (IOException e) {
				listStr = null;
				e.printStackTrace();
			}
		}
		return listStr;
	}
	/**
	 * @param text
	 * @param descPath
	 */
	public static void writeText(String text,String descPath){
		File root = new File(descPath.substring(0,descPath.lastIndexOf('\\')));
		if(!root.exists())root.mkdirs();
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(descPath));
			bw.write(text);
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * @param text
	 */
	public static void writeText(String text){
		File root = new File("C:\\__result\\");
		if(!root.exists())root.mkdirs();
		try {			
			BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\__result\\result.txt"));
			bw.write(text);
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @param listStr
	 * @param descPath
	 */
	public static void writeLine(List<? extends Object> listStr,String descPath){
		File root = new File(descPath.substring(0,descPath.lastIndexOf('\\')));
		if(!root.exists())root.mkdirs();
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(descPath));
			for(Object line:listStr){
				bw.write(line.toString());
				bw.newLine();
			}
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * @param listStr
	 */
	public static void writeLine(List<? extends Object> list){
		File root = new File("C:\\__result\\");
		if(!root.exists())root.mkdirs();
		try {			
			BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\__result\\result.txt"));
			for(Object obj:list){
				bw.write(obj.toString());
				bw.newLine();
			}
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
